package com.mvp.mvpdemo.base

import android.content.Context
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.OnLifecycleEvent
import com.mvp.mvpdemo.net.APIService
import com.mvp.mvpdemo.net.RetrofitClient
import com.retrofit.call_adapter.livedata_call_adapter.LiveDataCallAdapterFactory
import com.retrofit.retrofitutil.OkHttpLogInterceptor
import com.retrofit.retrofitutil.RetrofitBuilder
import retrofit2.converter.gson.GsonConverterFactory
import java.net.Proxy


abstract class BaseModel : IModel, LifecycleObserver {
    /**
     * apiService和apiService()是两种
     */
//1
    protected val apiService: APIService by lazy { RetrofitClient.getInstance().getApi() }

//2 构建retrofit
    fun apiService(
        context: Context,
        baseUrl: String,
       headers: Map<String, String>?,
        params: Map<String, String>?
    ): APIService {
        val retrofit = RetrofitBuilder.instance
            .addInterceptor(OkHttpLogInterceptor())
            .okHttpClientBuilderOption {//比如在外部设置okhttp 不走代理模式
                it.proxy(Proxy.NO_PROXY)}
            .baseUrl(baseUrl)
            .addConverterFactory(GsonConverterFactory.create())//json解析的实体
//            .addConverterFactory(ScalarsConverterFactory.create())//解析成字符串String
            .addCallAdapterFactory(LiveDataCallAdapterFactory())//livedata适配器
//            .addCallAdapterFactory(CoroutineCallAdapterFactory())//协程适配器
//            retrofit 2.6.0之后天然支持了协程 所以不需要适配器了
            .addHeaders(headers?:emptyMap())
            .addParams(params?:emptyMap())
            .build(context)
        return retrofit.create(APIService::class.java)
    }


    override fun attach() {

    }

    override fun detach() {

    }


    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    internal fun onDestroy(owner: LifecycleOwner) {
        detach()
    }

}